/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.session;

import entity.ContactEntity;
import entity.PersonEntity;
import java.util.List;
import javax.ejb.Stateless;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author wei
 */
@Stateless
public class ContactEntityFacade extends AbstractFacade<ContactEntity> {

    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public ContactEntityFacade() {
        super(ContactEntity.class);
    }

    public boolean checkEmailExistForUpdate(String inputEmail, Long personId){
        return !checkEmailDoesntExistForUpdate(inputEmail, personId);
    }
    
    private boolean checkEmailDoesntExistForUpdate(String inputEmail, Long personId) {
        ContactEntity newContact = getContactByEmail(inputEmail);
        return newContact==null || newContact.getPerson().getId()==personId;
    }
    
    public boolean checkEmailExist(String inputEmail) {
        return getContactsByEmail(inputEmail).size()>0;
    }

    public ContactEntity getContactByEmail(String inputEmail) {
        List<ContactEntity> contacts = getContactsByEmail(inputEmail); 
        if(contacts.isEmpty())
            return null;
        else
            return contacts.get(0);

    }
    
    public List<ContactEntity> getContactsByEmail(String inputEmail){
        Query query = (Query) em.createQuery("Select c from Contact c WHERE c.email=:inputEmail");
        query.setParameter("inputEmail", inputEmail);
        List<ContactEntity> contacts = query.getResultList();
        return contacts;
    }
}
